package cc.mrbird.febs.server.referral.controller;

import cc.mrbird.febs.common.core.entity.FebsResponse;
import cc.mrbird.febs.common.core.entity.QueryRequest;
import cc.mrbird.febs.common.core.entity.system.SystemUser;
import cc.mrbird.febs.common.core.exception.FebsException;
import cc.mrbird.febs.common.core.utils.FebsUtil;
import cc.mrbird.febs.server.referral.dto.WxUserDTO;
import cc.mrbird.febs.server.referral.entity.WxUser;
import cc.mrbird.febs.server.referral.service.IWxUserService;
import cc.mrbird.febs.server.referral.service.wx.WXRequest;
import cc.mrbird.febs.common.core.entity.ResponseCode;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信用户信息表 Controller
 *
 * @author MrBird
 * @date 2021-02-24 10:39:20
 */
@Slf4j
@Validated
@RestController
@RequestMapping("wxUser")
@RequiredArgsConstructor
public class WxUserController {
    @Value("${wx.appid}")
    private String  appid;
    @Value("${wx.secret}")
    private String  secret;
    private final IWxUserService wxUserService;
    public static String DOMAIN_API_OPENID = "https://api.weixin.qq.com/sns/jscode2session?appid=";

    /**
     * 用于演示
     */
    @GetMapping("show")
    public FebsResponse getRemoteUserList(QueryRequest request, SystemUser user) {
        FebsResponse febsResponse = new FebsResponse();
        febsResponse.put("user", "user-Show");
        return febsResponse;
    }

    @GetMapping
//    @PreAuthorize("hasAuthority('wxUser:list')")
    public FebsResponse getAllWxUsers(WxUser wxUser) {
        return new FebsResponse().data(wxUserService.findWxUsers(wxUser));
    }

    @GetMapping("list")
//    @PreAuthorize("hasAuthority('wxUser:list')")
    public FebsResponse wxUserList(QueryRequest request, WxUser wxUser) {
        log.info("查询微信用户第{}页，每页显示{}条数据", request.getPageNum(), request.getPageSize());
        Map<String, Object> dataTable = FebsUtil.getDataTable(this.wxUserService.findWxUsers(request, wxUser));
        return new FebsResponse().data(dataTable);
    }

    @PostMapping("getLogin")
    @ApiOperation(value = "获取登录信息",notes = "")
//    @PreAuthorize("hasAuthority('wxUser:add')")
    public FebsResponse getLogin(@RequestBody WxUserDTO wxUserDTO) throws FebsException {
        try {
            return this.wxUserService.saveWxUser(wxUserDTO);
        } catch (Exception e) {
            String message = "微信用户登录失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @PostMapping("/getOpenId")
    @ApiOperation(value = "调用微信接口获取openid",notes = "")
    public FebsResponse getOpenId(@RequestBody Map<String,Object> map) throws Exception {
        String wxCode = ObjectUtils.toString(map.get("code"));
        String url = DOMAIN_API_OPENID + appid + "&secret=" + secret + "&grant_type=authorization_code" + "&js_code=" + wxCode;
        log.info("getOpenId url --> {}", url);
        String openId = WXRequest.request(url, "");
        Map<String,Object> reqMap = new HashMap<>();
        reqMap.put("openId", openId);
        FebsResponse febsResponse = new FebsResponse();
        febsResponse.code(ResponseCode.SUCCESS.getCode());
        febsResponse.data(reqMap);
        return febsResponse;
    }


    @PostMapping
//    @PreAuthorize("hasAuthority('wxUser:add')")
    public void addWxUser(@Valid @RequestBody WxUser wxUser) throws FebsException {
        try {
            this.wxUserService.createWxUser(wxUser);
        } catch (Exception e) {
            String message = "新增WxUser失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @DeleteMapping
    @PreAuthorize("hasAuthority('wxUser:delete')")
    public void deleteWxUser(WxUser wxUser) throws FebsException {
        try {
            this.wxUserService.deleteWxUser(wxUser);
        } catch (Exception e) {
            String message = "删除WxUser失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    @PutMapping
    @PreAuthorize("hasAuthority('wxUser:update')")
    public void updateWxUser(WxUser wxUser) throws FebsException {
        try {
            this.wxUserService.updateWxUser(wxUser);
        } catch (Exception e) {
            String message = "修改WxUser失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
}
